<template>
  <a-modal
    :title="formInfo.id==undefined?'新增':'修改'"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="ruleForm"
        :model="formInfo"
        :label-col="$global.labelCol"
        :wrapper-col="$global.wrapperCol"
      >
            <a-row>
              <a-col :span="12">
            <a-form-model-item label="姓名" prop="name" :rules="$valid.required" :maxLength="50">
              <a-input v-model="formInfo.name" placeholder="请输入姓名"/>
            </a-form-model-item>
          </a-col>
                  <a-col :span="12">
            <a-form-model-item label="学校" prop="schid" :rules="$valid.required" :maxLength="50">
                <a-select
                        style="width: 100%"
                        placeholder="请选择学校"
                        @change="classChange"
                        optionFilterProp="children"
                        :disabled='schflag'
                        v-model="formInfo.schid">
                    <a-select-option
                            v-for="(demo,index) in schList"
                            :key="index.toString()"
                            :value="parseInt(demo.id)">
                        {{ demo.name }}
                    </a-select-option>
                </a-select>
            </a-form-model-item>
          </a-col>
            </a-row>
          <a-row>
              <a-col :span="12">
                  <a-form-model-item label="年级" prop="gradeid" :rules="$valid.required" :maxLength="50">
                      <a-select
                              style="width: 100%"
                              placeholder="请选择学校"
                              @change="classChange1"
                              optionFilterProp="children"
                              v-model="formInfo.gradeid">
                          <a-select-option
                                  v-for="(demo,index) in gradeList"
                                  :key="index.toString()"
                                  :value="parseInt(demo.id)">
                              {{ demo.name }}
                          </a-select-option>
                      </a-select>
                  </a-form-model-item>
              </a-col>
              <a-col :span="12">
                  <a-form-model-item label="班级" prop="classId" :rules="$valid.required" :maxLength="50">
                      <a-select
                              style="width: 100%"
                              placeholder="请选择班级"
                              @change="classChange2"
                              optionFilterProp="children"
                              v-model="formInfo.classId">
                          <a-select-option
                                  v-for="(demo,index) in classList"
                                  :key="index.toString()"
                                  :value="parseInt(demo.id)">
                              {{ demo.name }}
                          </a-select-option>
                      </a-select>
                      <!--<a-input-search
                              placeholder="点击右侧按钮选择班级"
                              v-model="formInfo.className"
                              onfocus="this.blur()"
                              @search="departCodeSearch">
                          <a-button slot="enterButton" icon="search">选择</a-button>
                      </a-input-search>-->
                  </a-form-model-item>
              </a-col>
          </a-row>
                <a-row>
              <a-col :span="12">
            <a-form-model-item label="编号" prop="shorter" :rules="$valid.required" :maxLength="50">
              <a-input v-model="formInfo.shorter" placeholder="请输入编号" readOnly />
            </a-form-model-item>
          </a-col>
                    <a-col :span="12">
                        <a-form-model-item label="身份证号" prop="identity"  :maxLength="50">
                            <a-input v-model="formInfo.identity" @blur="getPersonalInfoFromIDCard" placeholder="请输入身份证号"/>
                        </a-form-model-item>
                    </a-col>

            </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-model-item label="出生日期" prop="birthday" :rules="$valid.required" :maxLength="50">
                            <a-date-picker
                                    v-model="formInfo.birthday"
                                    inputReadOnly
                                    type="date"
                                    valueFormat="YYYY-MM-DD"
                                    format="YYYY-MM-DD"
                                    placeholder="请选择出生日期"
                                    style="width: 100%;"
                                    @change="getageBybirty"
                            />
                        </a-form-model-item>
                    </a-col>
              <a-col :span="12">
            <a-form-model-item label="年龄" prop="age" :rules="$valid.required" :maxLength="50">
              <a-input v-model="formInfo.age" placeholder="请输入年龄"/>
            </a-form-model-item>
          </a-col>

            </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-model-item label="性别" prop="sex" :rules="$valid.required" :maxLength="50">
                            <a-select v-model="formInfo.sex" placeholder="请选择性别">
                                <a-select-option
                                        v-for="(item) in this.$sysDictOptions('sex')"
                                        :key="item.k"
                                        :value="parseInt(item.k)">
                                    {{ item.v }}
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                  <a-col :span="12">
            <a-form-model-item label="家庭住址" prop="address"  :maxLength="50">
              <a-input v-model="formInfo.address" placeholder="请输入家庭住址"/>
            </a-form-model-item>
          </a-col>
            </a-row>
          <a-row>
              <a-col :span="12">
                  <a-form-model-item label="是否在校" prop="schoolFlag" :rules="$valid.required" :maxLength="50">
                      <a-select v-model="formInfo.schoolFlag" placeholder="请选择是否在校">
                          <a-select-option
                                  v-for="(item) in this.$sysDictOptions('schoolState')"
                                  :key="item.k"
                                  :value="parseInt(item.k)">
                              {{ item.v }}
                          </a-select-option>
                      </a-select>
                  </a-form-model-item>
              </a-col>
          </a-row>

      </a-form-model>
    </a-spin>
      <eye-class-window ref="departCodeRef" @ok="departCodeOk" :multiple-flag="false"></eye-class-window>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-modal>
</template>

<script>
  import { getAction, postAction } from '@/api/manage'
  import EyeClassWindow from "../eyeClass/EyeClassWindow";
  export default {
    name: 'EyeStudentEdit',
    components: {
        EyeClassWindow
    },
    data () {
      return {
        visible: false,
        confirmLoading: false,
        formInfo: {
          name: undefined,
          dingdingUnionId: undefined,
          classId: undefined,
          className: undefined,
          schid: undefined,
          schname: undefined,
          years: undefined,
          createTime: undefined,
          departCode: undefined,
          remark: undefined,
          shorter: undefined,
          sex: undefined,
          age: undefined,
          identity: undefined,
          birthday: undefined,
          address: undefined,
          gradeid:undefined,
          wx: '',
          gradename:'',
          schoolFlag:1
        },
          schList:[],
          gradeList:[],
          classList:[],
          schflag:false,
        drawerWidth: 800,
        url: {
          saveInfo: '/system/eyeStudent/save',
          getInfo: '/system/eyeStudent/info',
          classList: '/system/eyeClass/getList',
          getStudentNo:'/system/eyeStudent/getStudentNo'
        }
      }
    },
    created () {
        this.getclasslist(undefined,1)
    },
      watch(){

      },
    methods: {
      add () {
        this.edit()
      },
        add1 (schid) {
            this.formInfo.schid=schid
            this.schflag=true
            this.classChange()
            this.edit()
        },
        edit1 (record) {
            this.schflag=true

            this.edit(record)
        },
      edit (record) {
        this.$objToOverride(this.formInfo, record)
        if (this.formInfo.id) {
          getAction(this.url.getInfo, { 'id': record.id }).then(res => {

              this.formInfo = res.result.data
              if(this.formInfo.schid!=undefined){
                   this.formInfo.schid=this.formInfo.schid*1
                  this.getclasslist(this.formInfo.schid,2)
              }
              if(this.formInfo.gradeid!=undefined){
                   this.formInfo.gradeid=this.formInfo.gradeid*1
                  this.getclasslist(this.formInfo.gradeid,3)
              }
              if(this.formInfo.classId!=undefined){
                   this.formInfo.classId=this.formInfo.classId*1
              }

          })
        }else{

            getAction(this.url.getStudentNo, {  }).then(res => {
                console.log(res)
                this.formInfo.shorter=res.result.data.kvalue
            })
        }

        this.visible = true
      },
      // 确定
      handleSubmit () {
        // 触发表单验证
        this.confirmLoading = true
        this.$refs.ruleForm.validate(valid => {
          console.log(valid)
          if (valid) {
            postAction(this.url.saveInfo, this.formInfo).then(res => {
              this.$message.success(res.content)
              this.$emit('ok', this.formInfo)
              this.close()
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      // 关闭
      handleCancel () {
        this.close()
      },
      close () {
        this.$refs.ruleForm.resetFields()
        this.$objToReset(this.formInfo)
        this.$emit('close')
          this.gradeList=[]
          this.classList=[]
        this.visible = false
      },
      editorOk (val) {
        this.formInfo.content = val
      },
        // 搜索用户对应的归属部门API
        departCodeSearch () {
            this.$refs.departCodeRef.add([1],3)
        },
        // 获取用户对应部门弹出框提交给返回的数据
        departCodeOk (formData) {
            const departCodeNames = []
            const departCodeKeys = []
            let departCodeNameString = ''
            for (let i = 0; i < formData.departIdList.length; i++) {
                departCodeKeys.push(formData.departIdList[i].value)
                departCodeNames.push(formData.departIdList[i].title)
                departCodeNameString = departCodeNames.join(',')
            }
            if (departCodeKeys.length > 0) {
                this.formInfo.classId = departCodeKeys[0]
                this.formInfo.className = departCodeNameString
            }
        },
        classChange(){
            this.getclasslist(this.formInfo.schid,2)
            this.formInfo.gradeid=undefined
            this.formInfo.classId=undefined
        },
        classChange1(){
            this.getclasslist(this.formInfo.gradeid,3)
            this.formInfo.classId=undefined
        },
        classChange2(){

        },
        getclasslist(parentid,orgflag){
            getAction(this.url.classList, { 'parendId': parentid,'orgFlag':orgflag }).then(res => {
                this.$nextTick(() => {
                    if(orgflag==1){
                        this.schList=res.result.data
                    }else if(orgflag==2){
                        this.gradeList = res.result.data
                    }else if(orgflag==3){
                        this.classList = res.result.data
                    }

                })
            })
        },
         getPersonalInfoFromIDCard() {
          var idCard = this.formInfo.identity
          // 验证身份证号码长度是否为18位
          if (idCard.length !== 18) {
              this.$message.success('身份证号格式不正确')
          }else {
              // 提取出生年月日
              const year = idCard.substr(6, 4);
              const month = idCard.substr(10, 2);
              const day = idCard.substr(12, 2);
              const birthdate = `${year}-${month}-${day}`;
              this.formInfo.birthday = birthdate
              // 解析出生日期为Date对象
              const birthday = new Date(birthdate);

              // 如果出生日期无效，则返回错误
              if (isNaN(birthday.getTime())) {
                  this.$message.success('出生日期无效')
              }

              // 计算年龄
              const ageDiff = Date.now() - birthday.getTime();
              const age = Math.floor(ageDiff / (1000 * 60 * 60 * 24 * 365.25)); // 考虑闰年
              this.formInfo.age = age
              // 提取性别
              const genderCode = idCard.substr(16, 1);
              const gender = parseInt(genderCode) % 2 === 0 ? 0 : 1;
              this.formInfo.sex = gender
          }
        },
        getageBybirty(){
            const birthdate = this.formInfo.birthday
            console.log(birthdate)
            const birthday = new Date(birthdate);

            // 如果出生日期无效，则返回错误
            if (isNaN(birthday.getTime())) {
                this.$message.success('出生日期无效')
            }

            // 计算年龄
            const ageDiff = Date.now() - birthday.getTime();
            const age = Math.floor(ageDiff / (1000 * 60 * 60 * 24 * 365.25)); // 考虑闰年
            this.formInfo.age = age
        },
    }
  }
</script>
